package task

import (
	"cvevulner/common"
	"cvevulner/taskhandler"
	"errors"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"os"
)

// issue statistics mailing list
func IssueStatistics() error {
	defer common.Catchs()
	logs.Info("issue statistics task start")
	// The number of days the issue counts the mailing list
	beforeMonth, beErr := beego.AppConfig.Int("cve::before_month")
	if beErr != nil {
		beforeMonth = -3
	}
	prnum, prErr := beego.AppConfig.Int("crontab::prcnum")
	if prErr != nil {
		prnum = 100
	}
	owner := beego.AppConfig.String("gitee::owner")
	// Get the data source of the table
	err := taskhandler.IssueStatistics(beforeMonth, prnum, owner)
	logs.Info(err)
	logs.Info("issue statistics task end")
	return err
}

// Cve data email task with low credibility
func ProcCveLowCred() error {
	defer common.Catchs()
	logs.Info("cve credibility task start")
	// The number of days the issue counts the mailing list
	beforeDate, beErr := beego.AppConfig.Int("cve::cve_statistics_date")
	if beErr != nil {
		beforeDate = 30
	}
	prnum, prErr := beego.AppConfig.Int("crontab::prcnum")
	if prErr != nil {
		prnum = 100
	}
	// Get the data source of the table
	err := taskhandler.CveCredibilityStatistics(beforeDate, prnum)
	logs.Info(err)
	logs.Info("cve credibility task end")
	return err
}

func ProcSecLinkTemplate() error {
	defer common.Catchs()
	logs.Info("Add security bulletin link task started")
	// The number of days the issue counts the mailing list
	beforeDate, beErr := beego.AppConfig.Int("cve::sec_link_date")
	if beErr != nil {
		beforeDate = -30
	}
	prnum, prErr := beego.AppConfig.Int("crontab::prcnum")
	if prErr != nil {
		prnum = 100
	}
	owner := beego.AppConfig.String("gitee::owner")
	accessToken := os.Getenv("GITEE_TOKEN")
	if accessToken == "" || len(accessToken) < 1 {
		logs.Error("ProcSecLinkTemplate, issue token Get failed, current time: ", common.GetCurTime())
		return errors.New("Failed to get token in environment variable")
	}
	// Get the data source of the table
	err := taskhandler.ProcSecLinkTemplate(beforeDate, prnum, owner, accessToken)
	logs.Info(err)
	logs.Info("End of task of adding a link to a security bulletin")
	return err
}
